package com.io.viewgroup.image

import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.io.commonlib.helper.LogHelper
import com.io.viewgroup.Constans
import com.io.viewgroup.R
import com.io.viewgroup.image.adapter.ImageGroupViewAdapter
import com.io.viewgroup.image.interfaces.IOnClickPhotoAlbumListener
import com.io.viewgroup.image.interfaces.IOnClickTakePhotoListener

/**
 * Description:图片组合
 * 1，可以设置是否可以编辑，默认不可编辑
 * 2，在可以编辑的前提下，可以设置是否可以从相册选择，拍照默认支持
 * 3，支持设置是否可以预览大图，预览的大图支持手势放大缩小，左右切换
 * 4，支持设置一行显示几个图片，最多显示5张图
 * 2021-03-20 10:54
 * @author LiuMin
 */
class ImageGroupView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    RecyclerView(context, attrs, defStyleAttr) {

    private val TAG = ImageGroupView::class.java.simpleName
    private lateinit var mImageList: MutableList<String> //图片数据源
    private lateinit var mAdapter: ImageGroupViewAdapter
    private var isEditable: Boolean = false //控件是否可以编辑
    private var isSupportAlbum: Boolean = false //控件在支持编辑的前提下，是否支持从相册中选择
    private var isSupportPreview: Boolean = false //是否支持预览
    private var columnCount: Int = -1 //每一行显示的项数
    private var defaultImageSrc: Int = -1 //默认图片资源
    private var delImageSrc: Int = -1 //删除按钮图片资源
    private var itemHeight: Float = -1f //每一项的高度
    private var itemWidth: Float = -1f //每一项的宽度
    private var itemMarginHorizontal: Float = 0f //每一项的水平方向的Margin
    private var itemMarginVertical: Float = 0f //每一项的垂直方向的Margin
    private val MAX_COLUMN_COUNT = 3 //每一行最多显示的图片个数
    private var maxTotalCount = 3 //整个控件最多有多少张图片

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ImageGroupView)
        initView(typedArray)
        initRecyclerView()
        typedArray.recycle()
    }

    /**
     * 添加单个图片
     */
    fun addSingleImage(path: String) {
        val length = mImageList.size
        if (length == maxTotalCount) {
            mImageList.set(length - 1, path)
            mAdapter.notifyItemChanged(length - 1)
        } else {
            mImageList.set(length - 1, path)
            mImageList.add(length, Constans.DEFAULT_VALUE_IMAGE_GROUP_VIEW)
            mAdapter.notifyItemRangeChanged(length - 1, 2)
        }
        mAdapter.setImageList(mImageList)
    }

    /**
     * 设置数据源
     */
    fun setData(list: MutableList<String>?) {
        mImageList = mutableListOf()
        list?.let {
            LogHelper.d(TAG, "setData--数据原始长度：${list.size}")
            if (isEditable && list.size < maxTotalCount) {
                list.add(Constans.DEFAULT_VALUE_IMAGE_GROUP_VIEW)
            }
            LogHelper.d(TAG, "setData--数据中间长度：${list.size}")
            if (list.size > maxTotalCount) {
                mImageList = list.subList(0, maxTotalCount)
            } else {
                mImageList = list
            }
            LogHelper.d(TAG, "setData--数据新长度：${mImageList.size}")
        }?: let {
            if (isEditable) {
                mImageList.add(0, Constans.DEFAULT_VALUE_IMAGE_GROUP_VIEW)
            }
        }
        mAdapter.notifyData(mImageList)
    }

    /**
     * 设置IOnClickTakePhotoListener
     */
    fun setOnClickTakePhotoListener(listener: IOnClickTakePhotoListener) {
        mAdapter.mOnClickTakePhotoListener = listener
    }

    /**
     * 设置IOnClickPhotoAlbumListener
     */
    fun setOnClickPhotoAlbumListener(listener: IOnClickPhotoAlbumListener) {
        mAdapter.mOnClickPhotoAlbumListener = listener
    }

    /**
     * 点击删除按钮删除一张图片
     */
    fun onFinishDelImageListener(position: Int) {
        val length = mImageList.size
        if(position == length - 1){
            mImageList.set(length - 1, Constans.DEFAULT_VALUE_IMAGE_GROUP_VIEW)
            mAdapter.notifyItemChanged(length - 1)
        } else {
            mImageList.removeAt(position)
            mAdapter.notifyItemRemoved(position)
            mAdapter.notifyItemRangeChanged(position, mImageList.size - position)
        }
        mAdapter.setImageList(mImageList)
    }

    //region 私有方法
    /**
     * 根据属性设置初始化控件
     */
    private fun initView(typedArray: TypedArray) {
        isEditable =
            typedArray.getBoolean(R.styleable.ImageGroupView_isEditable, false)
        isSupportAlbum =
            typedArray.getBoolean(R.styleable.ImageGroupView_isSupportAlbum, false)
        isSupportPreview =
            typedArray.getBoolean(R.styleable.ImageGroupView_isSupportPreview, false)
        val count = typedArray.getInt(R.styleable.ImageGroupView_columnCount, 3)

        if (count > MAX_COLUMN_COUNT) {
            columnCount = MAX_COLUMN_COUNT
        } else {
            columnCount = count
        }

        defaultImageSrc =
            typedArray.getResourceId(R.styleable.ImageGroupView_defaultImageSrc, -1)
        delImageSrc =
            typedArray.getResourceId(R.styleable.ImageGroupView_delImageSrc, -1)
        itemHeight = typedArray.getDimension(R.styleable.ImageGroupView_itemHeight, -1f)
        itemWidth = typedArray.getDimension(R.styleable.ImageGroupView_itemWidth, -1f)
        itemMarginHorizontal =
            typedArray.getDimension(R.styleable.ImageGroupView_itemMarginHorizontal, 0f)
        itemMarginVertical =
            typedArray.getDimension(R.styleable.ImageGroupView_itemMarginVertical, 0f)
        //原则上控件所能接收的最大图片张数需要调用的时候传，如果不传，则按单行最大数走
        maxTotalCount = typedArray.getInt(R.styleable.ImageGroupView_totalMaxCount, columnCount)
    }

    /**
     * 初始化Adapter，并设置相关属性
     * 配置RecyclerView相关属性
     */
    private fun initRecyclerView() {
        mAdapter = ImageGroupViewAdapter(context, this)
        mAdapter.defaultImage = defaultImageSrc
        mAdapter.delImage = delImageSrc
        mAdapter.isEditable = isEditable
        mAdapter.isSupportAlbum = isSupportAlbum
        mAdapter.isSupportPreview = isSupportPreview
        if (itemHeight != -1f) {
            mAdapter.itemHeight = itemHeight
        }
        if (itemWidth != -1f) {
            mAdapter.itemWidth = itemWidth
        }
        if (itemMarginVertical != 0f) {
            mAdapter.itemMarginVertical = itemMarginVertical
        }
        if (itemMarginHorizontal != 0f) {
            mAdapter.itemMarginHorizontal = itemMarginHorizontal
        }
        mAdapter.maxTotalCount = maxTotalCount
        adapter = mAdapter
        layoutManager = GridLayoutManager(context, columnCount)
    }

    //endregion
}